package com.example.logindemo2.view

import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.logindemo2.R
import com.example.logindemo2.databinding.ActivityLoginBinding
import com.example.logindemo2.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.activity_login.*

/**
 * LoginActivity只做初始化和管理UI的工作
 */
class LoginActivity : BaseActivity() {

    private lateinit var binding: ActivityLoginBinding
    private lateinit var viewModel: LoginViewModel

    override fun initView() {
        super.initView()
        //DataBinding初始化
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
    }

    override fun initData() {
        super.initData()

        //ViewModel初始化
        viewModel = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        ).get(LoginViewModel::class.java)

        //绑定ViewMode和DataBinding
        binding.vm = viewModel

        //绑定生命周期, 建立感应
        binding.setLifecycleOwner(this);

        //观察用户名是否符合要求
        viewModel.username.observe(this, Observer {
            et_username.error =
                if (!viewModel.isUsernameValid()) getString(R.string.error_username) else null
            updateButtonStatus()
        })

        //观察密码是否符合要求
        viewModel.password.observe(this, Observer {
            et_password.error =
                if (!viewModel.isPasswordValid()) getString(R.string.error_password) else null
            updateButtonStatus()
        })

        //观察记住密码状态, 触发事件
        viewModel.rememberPwd.observe(this, Observer {
            viewModel.updateRememberPwdStatus()
        })
    }

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun onResume() {
        super.onResume()
        viewModel.recoverPwd()
    }

    fun updateButtonStatus() {
        bt_login.isEnabled = viewModel.isLoginButtonActivated()
        bt_login.background =
            if (bt_login.isEnabled) getDrawable(R.color.colorBotton) else getDrawable(R.color.colorGrey)
    }

    //    override fun onDestroy() {
//        super.onDestroy()
//        AppManager.instance.removeActivity(this)
//    }
}